package com.ruoyi.system.handier;



import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* @author : wenlong
* @date : 2023/06/25 19:12
* @modyified by :
*/
public class ChatWebSocketHandler extends  SimpleChannelInboundHandler<TextWebSocketFrame> {



    private static final Logger log = LoggerFactory.getLogger(ChatWebSocketHandler.class);

    private static final Logger esLog = LoggerFactory.getLogger("stash");
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        esLog.info("message test");
        log.info("与客户端建立连接，通道开启");
        //添加到通道组
        ChatChannelHandlerPool.channelGroup.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端连接断开，通道关闭");
        ChatChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {


        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            System.out.println(uri+"----------");
            //Map paramMap=getUrlParams(uri);
            //System.out.println("接收到的参数是："+ JSON.toJSONString(paramMap));
            //如果url包含参数，需要处理
            if(uri.contains("?")){
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            }

        }else if(msg instanceof TextWebSocketFrame){
            //正常的TEXT消息类型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            String text = frame.text();
            String flag=text.substring(0,text.indexOf(","));
            String vin=text.substring(text.indexOf(",")+1);
            System.out.println(vin);

            if (flag.equals("a")){
                sendMessage(ctx, "车辆未出现异常");
            }else {
                sendMessage(ctx, "车辆"+flag+"异常");
            }


        }
        super.channelRead(ctx, msg);

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    public void sendMessage(ChannelHandlerContext ctx, String msg){
        ctx.channel().writeAndFlush(new TextWebSocketFrame(msg));
    }


}
